package com.androidcentralmedias;

import android.util.Log;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.ArrayList;

public class Server implements Runnable {
	public ArrayList<String> fila = new ArrayList<String>();
	DatagramSocket theSocket = null;
	public Client client = new Client();

	public Server() {

		try {
			theSocket = new DatagramSocket(1236); //Server do Android e Client do PC na 1236
			// System.out.println("Server created and waiting for incomming connections...");
			Log.d("UDP","Server created and waiting for incomming connections...");
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			Log.d("UDP","Error creating the socket: " + e.getMessage());
		}
	}

	public void run() {
		String ultimo = new String();
		String parte = new String();
		DatagramPacket theRecievedPacket;
		byte[] inBuffer;
		try {
			ultimo = "DIFERETENTE?????1231215262re452264fd5s6a2f"; //soh para  nao ser null nem igual ao primeiro
			parte = null;
			// create some space for the text to send and recieve data
			inBuffer = new byte[500];
			// create a place for the client to send data too
			theRecievedPacket = new DatagramPacket(inBuffer, inBuffer.length);
			// wait for a client to request a connection
			while (true) {
				theSocket.receive(theRecievedPacket);
				if (!(ultimo.equals(new String(theRecievedPacket.getData(), 0,theRecievedPacket.getLength())))){  //checa para ver se nao eh soh uma duplicata, uma vez q o programa do PC manda varias copias até o android confirmar que chego alguma																//nesse caso a mensagem eh normal
						fila.add(new String(theRecievedPacket.getData(), 0,theRecievedPacket.getLength()));
						Log.d("UDP",new String(theRecievedPacket.getData(), 0,theRecievedPacket.getLength()));
						ultimo = new String(theRecievedPacket.getData(), 0,theRecievedPacket.getLength());		//lembra do ultimo comando, para checar se eh duplicata
					}
				Client.enviar(new String(theRecievedPacket.getData(), 0,theRecievedPacket.getLength()));  //mesmo que for uma duplicata eh bom mandar o check para dizer ao programa do PC que o android recebeu a String
			}
		} catch (IOException ExceIO) {
			Log.d("UDP","Error with client request : "+ ExceIO.getMessage());
		}

		// close the server socket
		
	}

}

